/**
 * 公共JavaScript工具函数
 */

// API基础地址
const API_BASE_URL = 'http://localhost:8080';

// 用户角色枚举
const UserRole = {
    NORMAL_USER: 0,
    SITE_ADMIN: 1,
    SUPER_ADMIN: 2
};

// 预约状态枚举
const AppointmentStatus = {
    PENDING: 0,      // 待接种
    COMPLETED: 1,    // 已完成
    CANCELLED: 2     // 已取消
};

// 疫苗类型枚举
const VaccineType = {
    COMMON: 0,       // 普通疫苗
    CHILD: 1,        // 儿童疫苗
    ADULT: 2         // 成人疫苗
};

/**
 * HTTP请求工具
 */
class HttpClient {
    /**
     * 发送GET请求
     */
    static async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = `${API_BASE_URL}${url}${queryString ? '?' + queryString : ''}`;

        try {
            const response = await fetch(fullUrl, {
                method: 'GET',
                headers: this.getHeaders()
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('GET请求失败:', error);
            throw error;
        }
    }

    /**
     * 发送POST请求
     */
    static async post(url, data = {}) {
        try {
            const response = await fetch(`${API_BASE_URL}${url}`, {
                method: 'POST',
                headers: this.getHeaders(),
                body: JSON.stringify(data)
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('POST请求失败:', error);
            throw error;
        }
    }

    /**
     * 发送PUT请求
     */
    static async put(url, data = {}) {
        try {
            const response = await fetch(`${API_BASE_URL}${url}`, {
                method: 'PUT',
                headers: this.getHeaders(),
                body: JSON.stringify(data)
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('PUT请求失败:', error);
            throw error;
        }
    }

    /**
     * 发送DELETE请求
     */
    static async delete(url) {
        try {
            const response = await fetch(`${API_BASE_URL}${url}`, {
                method: 'DELETE',
                headers: this.getHeaders()
            });
            return await this.handleResponse(response);
        } catch (error) {
            console.error('DELETE请求失败:', error);
            throw error;
        }
    }

    /**
     * 获取请求头
     */
    static getHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };

        const token = localStorage.getItem('token');
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }

        return headers;
    }

    /**
     * 处理响应
     */
    static async handleResponse(response) {
        // 检查响应状态
        if (!response.ok) {
            // 尝试解析错误信息
            try {
                const errorData = await response.json();
                throw new Error(errorData.errorMsg || errorData.msg || `请求失败: ${response.status}`);
            } catch (e) {
                throw new Error(`请求失败: ${response.status} ${response.statusText}`);
            }
        }

        // 获取响应文本
        const text = await response.text();

        // 如果响应为空，返回null
        if (!text || text.trim() === '') {
            return null;
        }

        // 尝试解析JSON
        try {
            const data = JSON.parse(text);

            if (data.code === 200) {
                return data.data;
            } else {
                // 创建错误对象，包含错误码和消息
                const error = new Error(data.errorMsg || data.msg || '请求失败');
                error.code = data.code;
                error.msg = data.msg || data.errorMsg;
                throw error;
            }
        } catch (e) {
            // 如果不是JSON格式，抛出错误
            console.error('响应解析失败:', text);
            throw new Error('服务器响应格式错误');
        }
    }
}

/**
 * 认证工具
 */
class Auth {
    /**
     * 保存登录信息
     */
    static saveLoginInfo(token, userInfo) {
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
    }

    /**
     * 获取Token
     */
    static getToken() {
        return localStorage.getItem('token');
    }

    /**
     * 获取用户信息
     */
    static getUserInfo() {
        const userInfo = localStorage.getItem('userInfo');
        return userInfo ? JSON.parse(userInfo) : null;
    }

    /**
     * 检查是否已登录
     */
    static isLoggedIn() {
        return !!this.getToken();
    }

    /**
     * 退出登录
     */
    static logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        window.location.href = '/login.html';
    }

    /**
     * 检查权限
     */
    static checkRole(requiredRole) {
        const userInfo = this.getUserInfo();
        if (!userInfo) {
            return false;
        }

        if (Array.isArray(requiredRole)) {
            return requiredRole.includes(userInfo.identityInfo);
        }

        return userInfo.identityInfo === requiredRole;
    }
}

/**
 * UI工具
 */
class UI {
    /**
     * 显示提示消息
     */
    static showMessage(message, type = 'info', duration = 3000) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type}`;
        alertDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 300px;
            animation: slideInRight 0.3s ease;
        `;

        const icon = this.getAlertIcon(type);
        alertDiv.innerHTML = `
            <i class="fas ${icon}"></i>
            <span>${message}</span>
        `;

        document.body.appendChild(alertDiv);

        setTimeout(() => {
            alertDiv.style.animation = 'slideOutRight 0.3s ease';
            setTimeout(() => {
                document.body.removeChild(alertDiv);
            }, 300);
        }, duration);
    }

    /**
     * 获取提示图标
     */
    static getAlertIcon(type) {
        const icons = {
            success: 'fa-check-circle',
            danger: 'fa-exclamation-circle',
            warning: 'fa-exclamation-triangle',
            info: 'fa-info-circle'
        };
        return icons[type] || icons.info;
    }

    /**
     * 显示加载状态
     */
    static showLoading(button) {
        // 如果传入了按钮参数，则禁用按钮并显示加载状态
        if (button) {
            button.disabled = true;
            button.dataset.originalText = button.innerHTML;
            button.innerHTML = '<span class="loading"></span> 加载中...';
        } else {
            // 如果没有传入按钮，显示全局加载遮罩
            let loadingOverlay = document.getElementById('globalLoadingOverlay');
            if (!loadingOverlay) {
                loadingOverlay = document.createElement('div');
                loadingOverlay.id = 'globalLoadingOverlay';
                loadingOverlay.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 9999;
                `;
                loadingOverlay.innerHTML = `
                    <div style="background: white; padding: 20px 40px; border-radius: 8px; text-align: center;">
                        <div class="loading" style="margin-bottom: 10px;"></div>
                        <div style="color: #333;">加载中...</div>
                    </div>
                `;
                document.body.appendChild(loadingOverlay);
            }
            loadingOverlay.style.display = 'flex';
        }
    }

    /**
     * 隐藏加载状态
     */
    static hideLoading(button) {
        // 如果传入了按钮参数，则恢复按钮状态
        if (button) {
            button.disabled = false;
            button.innerHTML = button.dataset.originalText;
        } else {
            // 如果没有传入按钮，隐藏全局加载遮罩
            const loadingOverlay = document.getElementById('globalLoadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.style.display = 'none';
            }
        }
    }

    /**
     * 确认对话框
     */
    static confirm(message, callback) {
        if (window.confirm(message)) {
            callback();
        }
    }
}

/**
 * 格式化工具
 */
class Format {
    /**
     * 格式化日期
     */
    static date(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    /**
     * 格式化日期时间
     */
    static datetime(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    }

    /**
     * 获取预约状态文本
     */
    static appointmentStatus(status) {
        const statusMap = {
            1: '待接种',
            2: '已接种',
            '-1': '已取消',
            0: '已逾期'
        };
        return statusMap[status] || '未知';
    }

    /**
     * 获取预约状态徽章类
     */
    static appointmentStatusBadge(status) {
        const badgeMap = {
            1: 'badge-warning',
            2: 'badge-success',
            '-1': 'badge-danger',
            0: 'badge-secondary'
        };
        return badgeMap[status] || 'badge-info';
    }

    /**
     * 获取疫苗类型文本
     */
    static vaccineType(type) {
        const typeMap = {
            0: '普通疫苗',
            1: '儿童疫苗',
            2: '成人疫苗'
        };

        if (type === null || type === undefined) {
            return '未知';
        }

        if (typeof type === 'string') {
            const trimmed = type.trim();
            if (trimmed === '') {
                return '未知';
            }
            const parsed = Number(trimmed);
            if (!Number.isNaN(parsed)) {
                const mapped = typeMap[parsed];
                return mapped || '未知';
            }
            // 已经是文本描述
            return trimmed;
        }

        const mapped = typeMap[type];
        return mapped || '未知';
    }

    /**
     * 获取用户角色文本
     */
    static userRole(role) {
        const roleMap = {
            0: '普通用户',
            1: '接种点管理员',
            2: '系统管理员'
        };
        return roleMap[role] || '未知';
    }

    /**
     * 获取家属关系文本
     */
    static familyRelationship(relationship) {
        const relationshipMap = {
            0: '父亲',
            1: '母亲',
            2: '配偶',
            3: '子女',
            4: '兄弟姐妹',
            5: '其他'
        };
        return relationshipMap[relationship] || '未知';
    }
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

/**
 * 检查并显示低库存预警（仅限接种点管理员页面）
 */
async function checkAndShowLowStockAlert() {
    try {
        // 检查sessionStorage中是否已关闭预警（本次会话）
        const alertClosed = sessionStorage.getItem('lowStockAlertClosed');
        if (alertClosed === 'true') {
            return; // 用户已关闭预警，本次会话不再显示
        }
        
        // 获取低库存预警列表（阈值10）
        const alerts = await HttpClient.get('/admin/inventory/low-stock-alert?threshold=10');
        
        if (alerts && Array.isArray(alerts) && alerts.length > 0) {
            // 有低库存预警，显示提示条
            const alertBar = document.getElementById('lowStockAlertBar');
            const alertText = document.getElementById('lowStockAlertText');
            const mainContent = document.getElementById('mainContent');
            
            if (alertBar && alertText && mainContent) {
                // 统计低库存疫苗数量
                const vaccineCount = new Set(alerts.map(a => a.vaccineId).filter(id => id != null)).size;
                alertText.textContent = `检测到 ${alerts.length} 个低库存预警（涉及 ${vaccineCount} 种疫苗），请及时补充库存`;
                
                alertBar.classList.add('show');
                mainContent.classList.add('has-alert');
            }
        }
    } catch (error) {
        console.error('检查低库存预警失败:', error);
    }
}

/**
 * 关闭低库存预警提示
 */
function closeLowStockAlert() {
    const alertBar = document.getElementById('lowStockAlertBar');
    const mainContent = document.getElementById('mainContent');
    
    if (alertBar) {
        alertBar.classList.remove('show');
    }
    if (mainContent) {
        mainContent.classList.remove('has-alert');
    }
    
    // 记录用户关闭了预警（本次会话有效）
    sessionStorage.setItem('lowStockAlertClosed', 'true');
}



